package com.jsb.laundry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsb.laundry.common.constant.CommonConstants;
import com.jsb.laundry.common.exception.BusinessException;
import com.jsb.laundry.common.exception.ErrorCode;
import com.jsb.laundry.common.exception.ThrowUtils;
import com.jsb.laundry.dao.JsbPostCommentsLikesMapper;
import com.jsb.laundry.dao.JsbPostCommentsMapper;
import com.jsb.laundry.dao.JsbPostsMapper;
import com.jsb.laundry.dao.UserDetailMapper;
import com.jsb.laundry.model.dto.posts.PostCommentQueryRequest;
import com.jsb.laundry.model.entity.*;
import com.jsb.laundry.model.vo.PostCommentVO;
import com.jsb.laundry.model.vo.PostsVO;
import com.jsb.laundry.model.vo.UserVO;
import com.jsb.laundry.service.JsbPostCommentsService;
import com.jsb.laundry.service.JsbPostLikesService;
import com.jsb.laundry.service.JsbPostsService;
import com.jsb.laundry.utils.SqlUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ching
* @description 针对表【jsb_post_comments(帖子评论表)】的数据库操作Service实现
* @createDate 2023-08-09 14:06:04
*/
@Service
public class JsbPostCommentsServiceImpl extends ServiceImpl<JsbPostCommentsMapper, JsbPostComments>
    implements JsbPostCommentsService {
    @Resource
    private JsbPostsService postService;
    @Resource
    private UserDetailMapper userDetailMapper;

    @Resource
    private JsbPostCommentsLikesMapper postCommentLikeMapper;

    @Override
    public int doAddPostComment(Integer postId, String userId, String content) {
        JsbPostComments postComment = new JsbPostComments();
        // 判断实体是否存在，根据类别获取实体
        JsbPosts post = postService.getById(postId);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 锁必须要包裹住事务方法
        JsbPostCommentsService postCommentsService = (JsbPostCommentsService) AopContext.currentProxy();
        synchronized (userId.intern()) {
            return postCommentsService.doAddPostCommentInner(postId, userId, content);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doAddPostCommentInner(Integer postId, String userId, String content) {
        JsbPostComments postComment = new JsbPostComments();
        postComment.setPostId(postId);
        postComment.setUserId(userId);
        postComment.setContent(content);
        boolean result = this.save(postComment);
        if (result) {
            // 评论数 + 1
            result = postService.update()
                    .eq("id", postId)
                    .setSql("comments = comments + 1")
                    .update();
            int newPostId = postComment.getId();
            return result ? newPostId: 0;
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    @Override
    public QueryWrapper<JsbPostComments> getQueryWrapper(PostCommentQueryRequest postCommentQueryRequest) {
        QueryWrapper<JsbPostComments> queryWrapper = new QueryWrapper<>();
        if (postCommentQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = postCommentQueryRequest.getSortField();
        String sortOrder = postCommentQueryRequest.getSortOrder();
        Long postId = postCommentQueryRequest.getPostId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(postId), "post_id", postId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstants.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public Page<PostCommentVO> getPostCommentPage(String loginUserId, Page<JsbPostComments> postCommentPage, HttpServletRequest request) {
        List<JsbPostComments> postCommentList = postCommentPage.getRecords();
        Page<PostCommentVO> postCommentVOPage = new Page<>(postCommentPage.getCurrent(), postCommentPage.getSize(), postCommentPage.getTotal());
        if (CollectionUtils.isEmpty(postCommentList)) {
            return postCommentVOPage;
        }
        // 填充信息
        List<PostCommentVO> postCommentVOList = postCommentList.stream().map(postComment -> {
            PostCommentVO postCommentVO = PostCommentVO.objToVo(postComment);
            String userId = postComment.getUserId();
            UserDetail user = new UserDetail();
            if (userId != null && !"".equals(userId)) {
                user = userDetailMapper.findUserDetailByUserId(userId);
            }
            UserVO userVO = new UserVO();
            if (user != null) {
                userVO.setUserId(user.getUserId());
                userVO.setUserName(user.getUserName());
                userVO.setUserAvatar(user.getUserAvatar());
            }
            postCommentVO.setUser(userVO);
            // 获取点赞
            QueryWrapper<JsbPostCommentsLikes> postCommentLikeQueryWrapper = new QueryWrapper<>();
            postCommentLikeQueryWrapper.in("comment_id", postComment.getId());
            postCommentLikeQueryWrapper.eq("user_id", loginUserId);
            JsbPostCommentsLikes postCommentsLikes = postCommentLikeMapper.selectOne(postCommentLikeQueryWrapper);
            postCommentVO.setHasLike(postCommentsLikes != null);

            return postCommentVO;
        }).collect(Collectors.toList());
        postCommentVOPage.setRecords(postCommentVOList);
        return postCommentVOPage;
    }
}




